// Copyright (C) 2009 Jesse Jones
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

using MmmDoc;
using MmmDoc.Database;
using System;
using System.Collections.Generic;
using System.Linq;

namespace MmmDoc.Html
{
	/// <summary>Generates an index pointing to each member of a type.</summary>
	internal sealed class GenerateTypeToc : WriteNormalHtml
	{
		public GenerateTypeToc(TypeDef type) : base(type.FileName() + "-toc.html", "type-toc.css")
		{
			m_type = type;
		}
		
		#region Protected Methods
		protected override string OnTitle
		{
			get {return m_type.FullName;}
		}
		
		protected override void OnWriteBodyContents(Writer writer)
		{
			writer.WriteStartTagLine("TABLE");
				writer.WriteStartTagLine("COLGROUP");
					writer.WriteElementLine("COL", null, "class", "section");
					writer.WriteElementLine("COL", null, "class", "member");
				writer.WriteEndTagLine("COLGROUP");
				
				writer.WriteStartTagLine("TBODY");
					if (m_type.DeclaringType != null)
						DoWriteDeclaringType(writer);
					else
						DoWriteNamespace(writer);
					DoWriteBlank(writer);
					
					if (m_type.IsInterface)
						DoWriteBaseInterfaces(writer);
					else
						DoWriteBaseClasses(writer);
					
					if (!m_type.IsDelegate)
						DoWriteSection(writer, "Constructors", "Constructors", m => m is ConstructorMember);
					
					DoWriteSection(writer, "Public Members", "Public_Members", m => m.Access == MemberAccess.Public && !(m is ConstructorMember));
					DoWriteSection(writer, "Protected OR Internal Members", "FamORAssem_Members", m => m.Access == MemberAccess.FamORAssem && !(m is ConstructorMember));
					DoWriteSection(writer, "Protected Members", "Family_Members", m => m.Access == MemberAccess.Family && !(m is ConstructorMember));
					DoWriteSection(writer, "Internal Members", "Assem_Members", m => m.Access == MemberAccess.Assem && !(m is ConstructorMember));
					DoWriteSection(writer, "Protected AND Internal Members", "FamANDAssem_Members", m => m.Access == MemberAccess.FamANDAssem && !(m is ConstructorMember));
					DoWriteSection(writer, "Private Members", "Private_Members", m => m.Access == MemberAccess.Private && !(m is ConstructorMember));
					
					if (m_type.NestedTypes.Length > 0)
						DoWriteNestedTypes(writer);
					
					if (m_type.DerivedTypes.Length > 0)
						if (m_type.IsInterface)
							DoWriteDerivedTypes(writer, "Implementors");
						else
							DoWriteDerivedTypes(writer, "Derived Classes");
				writer.WriteEndTagLine("TBODY");
			writer.WriteEndTagLine("TABLE");
		}
		#endregion
		
		#region Private Methods
		private const string NonBreakingWidthSpace = "\xA0";
		
		private void DoWriteNamespace(Writer writer)
		{
			string text = m_type.Namespace;
			if (text.Length == 0)
				text = "Globals";
			
			string link1 = "../namespaces-toc.html";
			string link2 = string.Format("top.contents.location='../namespaces-file.html#{0}';", text);
			
			writer.WriteStartTagLine("TR", "class", "section");
				writer.WriteStartTag("TD", "colspan", "2");
					writer.WriteElement("A", text, "target", "nav", "href", link1, "onClick", link2, "class", "section");
				writer.WriteEndTag("TD");
				writer.WriteLine();
			writer.WriteEndTagLine("TR");
		}
		
		private void DoWriteDeclaringType(Writer writer)
		{
			string text = m_type.DeclaringType.Name;
			
			string file = m_type.DeclaringType.FileName();
			string link1 = file + "-toc.html";
			string link2 = string.Format("top.contents.location='{0}';", file + "-file.html");
			
			writer.WriteStartTagLine("TR", "class", "section");
				writer.WriteStartTag("TD", "colspan", "2");
					writer.WriteElement("A", text, "target", "nav", "href", link1, "onClick", link2, "class", "section");
				writer.WriteEndTag("TD");
				writer.WriteLine();
			writer.WriteEndTagLine("TR");
		}
		
		private void DoWriteBaseInterfaces(Writer writer)
		{
			var bases = new List<TypeDef>();
			bases.Add(m_type);
			
			int i = 0;
			while (i < bases.Count)
			{
				foreach (TypeName type in bases[i].BaseTypes)
				{
					TypeDef td = type as TypeDef;
					
					if (td != null && td.IsInterface)
						bases.Add(td);
				}
				++i;
			}
			bases.RemoveAt(0);
			bases.Sort((lhs, rhs) => lhs.Name.CompareTo(rhs.Name));
			
			if (bases.Count > 0)
			{
				string text = bases.Count == 1 ? "Base Interface" : "Base Interfaces";
				DoWriteTypes(writer, text, bases);
				DoWriteBlank(writer);
			}
		}
		
		private void DoWriteBaseClasses(Writer writer)
		{
			var bases = new List<TypeDef>();
			bases.Add(m_type);
			
			int i = 0;
			while (i < bases.Count)
			{
				if (bases[i].BaseTypes.Length > 0)
				{
					TypeDef td = bases[i].BaseTypes[0] as TypeDef;
					
					if (td != null && !td.IsInterface)
						bases.Add(td);
				}
				++i;
			}
			bases.RemoveAt(0);
			bases.Reverse();
			
			if (bases.Count > 0)
			{
				string text = bases.Count == 1 ? "Base Class" : "Base Classes";
				DoWriteTypes(writer, text, bases);
				DoWriteBlank(writer);
			}
		}
		
		private void DoWriteNestedTypes(Writer writer)
		{
			var types = (from t in m_type.NestedTypes where t is TypeDef select (TypeDef) t).ToList();
			
			if (types.Count > 0)
			{
				types.Sort((lhs, rhs) => lhs.Name.CompareTo(rhs.Name));
				
				DoWriteTypes(writer, "Nested Types", types);
				DoWriteBlank(writer);
			}
		}
		
		private void DoWriteDerivedTypes(Writer writer, string text)
		{
			var types = new List<TypeDef>(m_type.DerivedTypes);
			
			if (types.Count > 0)
			{
				types.Sort((lhs, rhs) => lhs.Name.CompareTo(rhs.Name));
				
				DoWriteTypes(writer, text, types);
			}
		}
		
		private void DoWriteTypes(Writer writer, string text, List<TypeDef> bases)
		{
			writer.WriteStartTagLine("TR");
				writer.WriteElementLine("TD", text, "colspan", "2", "class", "section");
			writer.WriteEndTagLine("TR");
			
			foreach (TypeDef b2 in bases)
			{
				string file = b2.FileName();
				string link1 = file + "-toc.html";
				string link2 = string.Format("top.contents.location='{0}';", file + "-file.html");
				
				writer.WriteStartTagLine("TR");
					writer.WriteElement("TD", new string(NonBreakingWidthSpace[0], 4), "class", "indent");
					writer.WriteStartTag("TD");
						writer.WriteElement("A", b2.Name, "target", "nav", "href", link1, "onClick", link2, "class", "base");
					writer.WriteEndTag("TD");
					writer.WriteLine();
				writer.WriteEndTagLine("TR");
			}
		}
		
		private void DoWriteSection(Writer writer, string title, string target, Predicate<Member> predicate)
		{
			bool first = true;
			
			string name = m_type.FileName();
			
			for (int i = 0; i < m_type.Members.Length; ++i)
			{
				Member member = m_type.Members[i];
				if ((member.Definition == null || !member.Definition.Excluded) && predicate(member))
				{
					if (!m_type.IsEnum || member.Name != "value__")
					{
						if (first)
						{
							writer.WriteStartTagLine("TR", "class", "section");
								writer.WriteStartTag("TD", "colspan", "2");
									writer.WriteElement("A", title, "href", name + "-file.html#" + target, "target", "contents", "class", "section");
								writer.WriteEndTag("TD");
								writer.WriteLine();
							writer.WriteEndTagLine("TR");
							first = false;
						}
						
						writer.WriteStartTagLine("TR");
							writer.WriteElement("TD", new string(NonBreakingWidthSpace[0], 4), "class", "indent");
							writer.WriteStartTag("TD");
								writer.WriteElement("A", member.Key, "href", name + "-file.html#M" + i, "target", "contents", "class", "member");
							writer.WriteEndTag("TD");
							writer.WriteLine();
						writer.WriteEndTagLine("TR");
					}
				}
			}
			
			if (!first)
				DoWriteBlank(writer);
		}
		
		private void DoWriteBlank(Writer writer)
		{
			writer.WriteStartTagLine("TR");
				writer.WriteElement("TD", NonBreakingWidthSpace, "colspan", "2", "class", "separator");
				writer.WriteLine();
			writer.WriteEndTagLine("TR");
		}
		#endregion
		
		#region Fields
		private TypeDef m_type;
		#endregion
	}
}
